package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import cn.jpush.android.api.JPushInterface
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.database.OrderDB
import com.two.screen.water.balance.bean.database.OrderDBDao
import com.two.screen.water.balance.bean.database.UserDB
import com.two.screen.water.balance.bean.database.UserDBDao
import com.two.screen.water.balance.listener.MyObserver
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.net.api.OrderApi
import com.two.screen.water.balance.permission.AlertDialog
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.print.bean.PrintConnectBean
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import kotlinx.android.synthetic.main.activity_jiao_jie.*
import java.lang.StringBuilder

@Route(path = ARouterUtils.JiaoJieActivity)
class JiaoJieActivity : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_jiao_jie

    private var isAutoConnectPrint = false


    override fun initView(savedInstanceState: Bundle?) {

    }

    override fun initData() {
        isAutoConnectPrint = SPUtils.getBoolean(Params.isAutoJiaoJiePrint)
        initChooseIv()
        getUserData()
    }

    private fun getUserData() {
        Observable.create(ObservableOnSubscribe<UserDB> { e ->
            val userDB = App.mDaoSession?.userDBDao?.queryBuilder()
                ?.where(UserDBDao.Properties.Id.eq(DataApi.mUserId))
                ?.offset(0)?.limit(1)
                ?.list()
                ?.firstOrNull()
            if (userDB != null) e.onNext(userDB) else e.onError(Throwable("找不到用户!"))
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(this@JiaoJieActivity))
            .subscribe(object : MyObserver<UserDB>() {
                @SuppressLint("SetTextI18n", "CheckResult")
                override fun onNext(userDB: UserDB) {
                    mUserInfoTv.text = "收银员:${userDB.userName}   工号:${userDB.accounts}   登录时间:${userDB.updateTimeName}"
                    mProductListTv.setOnClickListener {
                        d("userDB:${CommUtils.gson.toJson(userDB)}")
                        ARouter.getInstance()
                            .build(ARouterUtils.JiaoJieProductListActivity)
                            .withString("mUpdateTime", userDB.updateTime.toString())
                            .withString("mUserId", userDB.id.toString())
                            .withString("mUserName", userDB.userName)
                            .navigation()
                    }
                    getOrderStatistics(userDB)
                }
            })

    }

    private fun getOrderStatistics(userDB: UserDB) {
        //总单据数
        Observable.create(ObservableOnSubscribe<MutableList<OrderDB>> { e ->
            val totalList = App.mDaoMaster?.newSession()?.orderDBDao?.queryBuilder()
                //?.where(OrderDBDao.Properties.OrderStatus.eq(OrderApi.ORDER_STATUS_PAID))
                ?.where(OrderDBDao.Properties.OrderType.eq(OrderApi.ORDER_TYPE_NORMAL))
                ?.where(OrderDBDao.Properties.UserId.eq(userDB.id))
                ?.where(OrderDBDao.Properties.CreateTime.ge(userDB.updateTime))//大于登录时间
                ?.list()

            if (totalList != null && totalList.isNotEmpty()) e.onNext(totalList) else e.onError(Throwable("找不到数据!"))
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(this@JiaoJieActivity))
            .subscribe(object : MyObserver<MutableList<OrderDB>>() {
                @SuppressLint("SetTextI18n", "CheckResult")
                override fun onNext(list: MutableList<OrderDB>) {
                    var reverseList = list.filter { it.orderStatus == OrderApi.ORDER_STATUS_REVERSE_CHECKOUT }
                    var returnList = list.filter { it.orderStatus == OrderApi.ORDER_STATUS_RETURN }


                    var totalPayList = list.filter { it.orderStatus == OrderApi.ORDER_STATUS_PAID }.toMutableList()
                    var cashPayList = list.filter { it.orderStatus == OrderApi.ORDER_STATUS_PAID && it.payType.toInt() == OrderApi.PAY_TYPE_CASH }.toMutableList()
                    var wetchVipPayList = list.filter { it.orderStatus == OrderApi.ORDER_STATUS_PAID && it.payType.toInt() == OrderApi.PAY_TYPE_WETCH_VIP }.toMutableList()
                    //var juhePayList = list.filter { it.orderStatus == OrderApi.ORDER_STATUS_PAID && it.payType.toInt() == OrderApi.PAY_TYPE_JUHE }.toMutableList()
                    var scanQrPayList = list.filter { it.orderStatus == OrderApi.ORDER_STATUS_PAID && it.payType.toInt() == OrderApi.PAY_TYPE_SCAN_QR }.toMutableList()


                    var sb = StringBuilder()
                    sb.appendLine("总单数:${list.size},门店:${list.size},退货:${returnList.size},反结账:${reverseList.size};")
                    sb.appendLine(
                        "总实收金额:${getRealTotalPrice(totalPayList)},现金实收:${getRealTotalPrice(cashPayList)}," +
                                "聚合支付实收:${getRealTotalPrice(wetchVipPayList)},扫码收款:${getRealTotalPrice(scanQrPayList)};"
                    )
                    sb.appendLine(
                        "总销售额:${getSaleTotalPrice(totalPayList)},现金:${getSaleTotalPrice(cashPayList)}," +
                                "聚合支付:${getSaleTotalPrice(wetchVipPayList)},扫码收款:${getSaleTotalPrice(scanQrPayList)};"
                    )
                    mTempTv.text = sb.toString()

                    //封装打印数据
                    var printConnectBean = PrintConnectBean().apply {
                        this.title = "交接班单据"
                        this.operationName = userDB.userName
                        this.startTime = userDB.updateTimeName
                        this.endTime = CommUtils.toYMD_HMS(System.currentTimeMillis() / 1000)

                        this.billTotal = list.size.toString()
                        this.billShop = list.size.toString()
                        this.billReturn = returnList.size.toString()
                        this.billReverse = reverseList.size.toString()

                        this.realTotalPrice = getRealTotalPrice(totalPayList)
                        this.realCashPrice = getRealTotalPrice(cashPayList)
                        this.realWetchVipPrice = getRealTotalPrice(wetchVipPayList)
                        //this.realJuHePrice = getRealTotalPrice(juhePayList)
                        this.realScanQrPrice = getRealTotalPrice(scanQrPayList)

                        this.saleTotalPrice = getSaleTotalPrice(totalPayList)
                        this.saleCashPrice = getSaleTotalPrice(cashPayList)
                        this.saleWetchVipPrice = getSaleTotalPrice(wetchVipPayList)
                        //this.saleJuHePrice = getSaleTotalPrice(juhePayList)
                        this.saleScanQrPrice = getSaleTotalPrice(scanQrPayList)
                    }

                    mJiaoJieTv.setOnClickListener {
                        //TODO:检查是否有挂单
                        Observable.create(ObservableOnSubscribe<Boolean> { e ->
                            val pendingList = App.mDaoMaster?.newSession()?.orderDBDao?.queryBuilder()
                                //?.where(OrderDBDao.Properties.OrderStatus.eq(OrderApi.ORDER_STATUS_PAID))
                                ?.where(OrderDBDao.Properties.OrderType.eq(OrderApi.ORDER_TYPE_PENDING))
                                ?.where(OrderDBDao.Properties.UserId.eq(userDB.id))
                                ?.where(OrderDBDao.Properties.CreateTime.ge(userDB.updateTime))//大于登录时间
                                ?.list()
                            if (pendingList != null && pendingList.isNotEmpty()) e.onNext(true) else e.onNext(false)
                        })
                            .compose(RxUtils.io())
                            .compose(RxUtils.aLifecycle(this@JiaoJieActivity))
                            .subscribe(object : MyObserver<Boolean>() {
                                @SuppressLint("SetTextI18n", "CheckResult")
                                override fun onNext(hasPendingOrder: Boolean) {
                                    if (hasPendingOrder) {
                                        AlertDialog.newBuilder(this@JiaoJieActivity)
                                            .setCancelable(true)
                                            .setTitle(R.string.tips)
                                            .setMessage("有未收银的挂单，确认继续交接班吗？")
                                            .setPositiveButton(R.string.confirm) { dialog, which ->
                                                dialog.dismiss()
                                                confirmConnect(userDB, printConnectBean)
                                            }
                                            .setNegativeButton(R.string.cancel) { dialog, which -> dialog.dismiss() }
                                            .show()
                                    } else {
                                        confirmConnect(userDB, printConnectBean)
                                    }
                                }
                            })
                    }
                }
            })
    }

    private fun confirmConnect(userDB: UserDB, printConnectBean: PrintConnectBean) {
        JPushInterface.deleteAlias(this, 0)
        //TODO：开始交接->把updateTime置空
        userDB.updateTime = null
        userDB.updateTimeName = null
        App.mDaoMaster?.newSession()?.userDBDao?.update(userDB)
        //SPUtils.clear()
        ARouter.getInstance()
            .build(ARouterUtils.LoginActivity)
            .navigation()
        overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom)
        ActivityCollector.finishAll()
        //TODO:是否打印
        if (isAutoConnectPrint) PrinterAll.printConnectStatics(printConnectBean)
    }


    fun getSaleTotalPrice(list: MutableList<OrderDB>?): String {
        var total = 0.0
        list?.forEach {
            total += it.totalPrice.toDouble()
        }
        return String.format("%.2f", total)
    }

    fun getRealTotalPrice(list: MutableList<OrderDB>?): String {
        var total = 0.0
        list?.forEach {
            total += it.realPrice.toDouble()
        }
        return String.format("%.2f", total)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initListener() {
        mGoBackLayout.setOnClickListener { goBack() }


        mPrintTicketLayout.setOnClickListener {
            isAutoConnectPrint = !isAutoConnectPrint
            SPUtils.putBoolean(Params.isAutoJiaoJiePrint, isAutoConnectPrint)
            initChooseIv()
        }
    }

    private fun initChooseIv() {
        mPrintTicketIv.setImageResource(if (isAutoConnectPrint) R.drawable.svg_choose_selected else R.drawable.svg_choose_unselected)
    }
}